package pile.customer.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pile.Customer;
import pile.customer.entity.CustomerService;
import pile.customer.entity.ResponseResult;
import pile.customer.params.customerService.CustomerServiceVO;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Log4j2
public class JwtUtils {

    // token时效：1年
    public static final long EXPIRE = 1000 * 60 * 60 * 24 *365;
    // 签名哈希的密钥，对于不同的加密算法来说含义不同
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWfs2jZWwewrPHO";

    /**
     * 根据用户id和昵称生成token
     * @param
     * @return JWT规则生成的token
     */
    public static String getJwtToken(CustomerService customerService){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("accountNumber", customerService.getAccountNumber())
                .claim("customerServiceId", customerService.getCustomerServiceId())
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken token字符串
     * @return 如果token有效返回true，否则返回false
     */
    public static boolean checkToken(String jwtToken, HttpServletResponse response,String path) {

        int code=HttpStatus.UNAUTHORIZED.value();


        ResponseResult result = new ResponseResult(code, "token失效!请重新登录！");
        String json = JSON.toJSONString(result);

        //判断JWT是否为空
        if(StringUtils.isEmpty(jwtToken)){
            WebUtils.renderString(response,json);
            return false;
        }
        try {
            //判断JWT是否有效
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            log.error("token失效!请重新登录！jwtToken:" + jwtToken+"请求路径:"+path);
            WebUtils.renderString(response,json);
            return false;
        }
        return true;
    }

    /**
     * 根据jwtToken获取用户的id
     * @return
     *
     */
    public static CustomerServiceVO getByCustomerServiceVO(){
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String bussinessToken = request.getHeader("CustomerToken");
        if(bussinessToken==null){
           String split[]  = request.getHeader("Authorization").split(" ");
            bussinessToken = split[1];
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(bussinessToken);
        Claims claims = claimsJws.getBody();
        //使用Json把对象转换为UserVO
        CustomerServiceVO customerServiceVO =  JSONObject.parseObject(JSONObject.toJSONString(claims), CustomerServiceVO.class);
        return customerServiceVO;
    }
}
